package com.apestech.formwork.condition;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.SaveTableCallback;
import com.apestech.framework.sql.callback.SaveTablesCallback;
import com.apestech.framework.xml.condition.modul.Account;
import com.apestech.framework.xml.plugin.modul.SpecialField;
import com.apestech.framework.xml.table.modul.Tables;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-01-30-19:13
 */
public class ExecAccountSave implements SaveTableCallback {

    private boolean insert;
    private boolean query;
    private Account.Bill bill;
    private JSONObject keyMap;
    private SaveTablesCallback saveTablesCallback;

    public ExecAccountSave(Account.Bill bill, boolean insert, boolean query, JSONObject keyMap, SaveTablesCallback saveTablesCallback){
        this.bill=bill;
        this.insert=insert;
        this.query=query;
        this.keyMap=keyMap;
        this.saveTablesCallback=saveTablesCallback;
    }

    @Override
    public boolean before(String tabName) throws Exception {
        return true;
    }

    @Override
    public void write(String tabName, JSONObject input, int index, SqlSession session) throws Exception {
        Account.UpdateTable updateTable=bill.getUpdateTable(tabName);
        if(updateTable!=null){
            String update=updateTable.getBillTableName();
            String keyField=updateTable.getKeyField();
            if(input.get(keyField)!=null){
                if(!insert){
                    if(index==0){
                        if(query){
                            JSONArray qlist=session.getForJSON().table(update, keyMap);
                            int qlen=qlist.size();
                            for(int i=0; i<qlen; i++) saveTablesCallback.delete(update, qlist.get(i), session);
                        }
                        JSONObject m=new JSONObject();
                        m.putAll(keyMap);
                        m.put("table_key","");
                        m.put("autoCompletion","1");
                        session.getForUpdate().deleteTable(update, m);
                    }
                }
                saveTablesCallback.insert(update, input, index, session);
                session.getForUpdate().insertTable(update, input);
            }
        }
    }

    @Override
    public String after(String tabName, JSONObject input) throws Exception {
        return null;
    }
}
